package com.example.service;

import cn.hutool.core.date.DateUtil;
import com.example.entity.Comment;
import com.example.entity.SeriesComment;
import com.example.mapper.SeriesCommentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SeriesCommentService {

    @Resource
    private SeriesCommentMapper seriesCommentMapper;

    public PageInfo selectPage(SeriesComment seriesComment, Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<SeriesComment> seriesComments = seriesCommentMapper.selectAll(seriesComment);
        List<SeriesComment> replies = seriesCommentMapper.selectReply(seriesComment);
        List<SeriesComment> list = new ArrayList<>();
        for(SeriesComment rootComment : seriesComments){
            for(SeriesComment reply : replies){
                if(reply.getPid().equals(rootComment.getId())){
                    list.add(reply);
                }
            }
            rootComment.setChildren(list);
            list = new ArrayList<>();
        }
        return PageInfo.of(seriesComments);
    }

    public void delete(Integer id){
        seriesCommentMapper.deleteById(id);
    }

    public void deleteBySeriesId(Integer id){
        seriesCommentMapper.deleteBySeriesId(id);
    }

    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            seriesCommentMapper.deleteById(id);
        }
    }

    public void add(SeriesComment seriesComment){
        seriesComment.setTime(DateUtil.now());
        seriesCommentMapper.insert(seriesComment);
    }

    // 查询不同评论数量
    public List<SeriesComment> countComment(Integer id){
        return seriesCommentMapper.countComment(id);
    }
}
